/*
 * @Author: dingyuwen ding_yuwen@163.com
 * @Date: 2023-02-08 18:03:19
 * @LastEditTime: 2023-10-20 17:36:08
 * @LastEditors: DingYuwen 43669762+DingYuwen@users.noreply.github.com
 * @Description:
 */
import { resolve } from 'path';

import react from '@vitejs/plugin-react-swc';
import { visualizer } from 'rollup-plugin-visualizer';
import { defineConfig, loadEnv, PluginOption } from 'vite';
import eslint from 'vite-plugin-eslint';
import tsconfigPaths from 'vite-tsconfig-paths';
export default defineConfig(({ mode }) => {
  // 根据当前工作目录中的 `mode` 加载 .env 文件
  // 设置第三个参数为 '' 来加载所有环境变量，而不管是否有 `VITE_` 前缀。
  const {
    BASE_URL,
    VITE_APP_WEB_API_URL,
    VITE_APP_AIGC_API_URL,
    VITE_APP_FILE_URL,
    VITE_APP_SOCKET_URL,
  } = loadEnv(mode, process.cwd(), '');
  return {
    base: BASE_URL,
    plugins: [
      react(),
      eslint({
        exclude: ['**/dist/**', '**/node_modules/**'],
      }),
      tsconfigPaths(),
      visualizer() as unknown as PluginOption,
    ],
    resolve: {
      alias: {
        '@': resolve(__dirname, './src'),
      },
    },
    server: {
      proxy: {
        '/web': {
          target: `${VITE_APP_WEB_API_URL}/web`,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/web/, ''),
        },
        '/images/upload': {
          target: `${VITE_APP_AIGC_API_URL}/`,
          changeOrigin: true,
        },
        '/images': {
          target: `${VITE_APP_FILE_URL}/`,
          changeOrigin: true,
        },
        // Proxy socket.io to the nodes socketio server
        '/api/ws/socket.io': {
          target: VITE_APP_SOCKET_URL,
          rewrite: (path) =>
            path.replace(/^\/api\/ws\/socket.io/, '/ws/socket.io'),
          ws: true,
        },
        // Proxy openapi schema definiton
        '/openapi.json': {
          target: `${VITE_APP_AIGC_API_URL}/openapi.json`,
          rewrite: (path) => path.replace(/^\/openapi.json/, ''),
          changeOrigin: true,
        },
        // proxy nodes api
        '/api/v1': {
          target: `${VITE_APP_AIGC_API_URL}/api/v1`,
          rewrite: (path) => path.replace(/^\/api\/v1/, ''),
          changeOrigin: true,
        },
      },
    },
    build: {
      chunkSizeWarningLimit: 1500,
      // outDir: resolve(__dirname, '../../dist'),
      rollupOptions: {
        output: {
          manualChunks: (id) => {
            if (id.includes('node_modules/lodash')) {
              return 'lodash';
            }
            if (
              id.includes('packages/theme') ||
              id.includes('i18next') ||
              id.includes('packages/locales')
            ) {
              return 'common-chunk';
            }
          },
        },
      },
    },
  };
});
